import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Layout from '@/layout'
import Cookies from 'js-cookie'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menu:null,
    buttens:null,
  }
}
const state = getDefaultState()

const mutations = {
  //重制vux存储对象
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
    //vuex存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //vuex存储用户名
  SET_NAME: (state, name) => {
    state.name = name
  },
  //vuex存储用户头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  //vuex存储菜单不使用vuex来存储菜单 因为页面刷新vuex 会丢失
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_BUTTEN:(state,buttens)=>{
    state.buttens = buttens
  }
}
function  changeTree(tree,parentPath){
  tree.forEach(temp => {
   if(temp.component==='Layout'){
    temp.component=Layout
    temp.redirect="/Layout"
   }
   else{
    //  const component =resolve => require([`@/views/${temp.path}`], resolve)
    // const component =resolve => require(['@/views/'+temp.path], resolve)
    const component =resolve => require(['@/views'+parentPath+"/"+temp.path], resolve)
    temp.component=component
    temp.meta.path=parentPath+"/"+ temp.meta.path
   }
   if(temp.children.length>0){
    changeTree(temp.children,temp.path)
   }
   else{
     temp.alwaysShow=false;
     delete temp.children
   }
   

 });
 return tree;
}
var RoleIdList={
  roleIdList:[]
};
const actions = {
  
  //设置页面butten权限
  setButten({ commit }, buttens) {
    return new Promise(resolve => {
      commit('SET_BUTTEN', buttens)
      resolve()
    })
  },
  // user login
  login({ commit }, userInfo) {
    // const { u_name, u_pass_word } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        commit('SET_TOKEN', response.Body.UserInfo.token)
        commit('SET_NAME', response.Body.UserInfo.u_name)
        // localStorage.setItem('u_name',response.Body.UserInfo.u_name);
        sessionStorage.setItem('u_name', response.Body.UserInfo.u_name); 
        Cookies.set('u_name', response.Body.UserInfo.u_name)
        // commit('SET_MENU', 'bb')
        setToken(response.Body.UserInfo.token)//cookie 不设置过期事件 就是浏览器关闭自动过期清除
        RoleIdList.roleIdList=response.Body.RoleIdList;
      
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
         if (!response.bodyList) {
          return reject('获取用户信息失败，请重新登录')
        }
       var tree= changeTree(response.bodyList)
       console.log(tree)
      //  var errMenu={ path: '*', redirect: '/404', hidden: true }
      //  tree.push(errMenu)
      //  sessionStorage.setItem('Menu',JSON.stringify(tree))
      //sessionStorage.setItem('Menu',JSON.stringify(response.bodyList))//不用sessionStorage存储路由路由丢失就重新获取
       commit('SET_MENU',tree)//不使用vuex来存储菜单 因为页面刷新vuex 会丢失（路由丢失就重新获取一次）
        // commit('SET_MENU', tree)
        // const { data } = response
        // if (!data) {
        //   return reject('Verification failed, please Login again.')
        // }
        // const { name, avatar } = data
        // commit('SET_NAME', 'as')
        // commit('SET_AVATAR', avatar)
        // resolve(data)
       
        resolve(tree)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout({token:state.token,u_name: Cookies.get('u_name')}).then(() => {
        removeToken() // must remove  token  first
        Cookies.remove('u_name')
        sessionStorage.removeItem('u_name');
        // sessionStorage.removeItem('Menu')
        // location.href="http://localhost:8080/"
         location.reload();// resetRouter 由于清空不掉路由 只能用刷新 来变相清空路由
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      Cookies.remove('u_name')
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

